//
//  YCBankCardTextField.m
//  DemoCustomTxtFld
//
//  Created by tangkexiong on 16/1/25.
//  Copyright © 2016年 tangkexiong. All rights reserved.
//

#import "YCBankCardTextField.h"

@implementation YCBankCardTextField

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if (self) {
        [self _configView];
    }
    
    return self;
}

- (void)awakeFromNib {
    [super awakeFromNib];
    
    [self _configView];
}

- (void)_configView {
    self.keyboardType = UIKeyboardTypeNumberPad;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_textDidChange:) name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UITextFieldTextDidChangeNotification object:nil];
}

- (void)willMoveToSuperview:(UIView *)newSuperview {
    self.text = [self _convertToBankCard:self.text];
}

- (void)setText:(NSString *)text {
    [super setText:[self _convertToBankCard:self.text]];
}

#pragma mark - NSNotification

- (void)_textDidChange:(NSNotification *)notifiction {
    self.text = [self _convertToBankCard:self.text];
}

- (NSString *)_convertToBankCard:(NSString *)str {
    if (str) {
        NSString *strTemp = [[str componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789"] invertedSet]] componentsJoinedByString:@""];
        NSMutableString *strMutable = [[NSMutableString alloc] init];
        while (strTemp.length > 0) {
            NSString *subStr = [strTemp substringToIndex:MIN(strTemp.length, 4)];
            [strMutable appendString:subStr];
            if (subStr.length == 4) {
                [strMutable appendString:@" "];
            }
            strTemp = [strTemp substringFromIndex:MIN(strTemp.length, 4)];
        }
        
        return [strMutable stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    } else {
        return nil;
    }
}

@end
